package com.ruoyi.epidemic.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.epidemic.domain.*;
import com.ruoyi.epidemic.mapper.YqInfoCollectMapper;
import com.ruoyi.epidemic.service.IEpidemicUserDeptBashService;
import com.ruoyi.epidemic.service.IWxCpUserService;
import com.ruoyi.epidemic.service.IYqInfoCollectService;
import com.ruoyi.epidemic.util.MyExcelUtil;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 疫情防控信息收集Service业务层处理
 *
 * @author ruoyi
 * @date 2022-04-04
 */
@Service
public class YqInfoCollectServiceImpl implements IYqInfoCollectService
{
    @Autowired
    private YqInfoCollectMapper yqInfoCollectMapper;

    @Autowired
    IWxCpUserService IWxCpUserService;

    @Autowired
    private IEpidemicUserDeptBashService epidemicUserDeptBashService;

    private static final DateTimeFormatter FORMAT_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
    protected Logger logger = LoggerFactory.getLogger(YqInfoCollectServiceImpl.class);

    private static final String aduitComplete="1";
    private static final String notaduit="99";
    //内外部人员标识
    private static final String INTERNAL = "N";
    private static final String EXTERNAL = "Y";

    //导出数据数据类型   1:未填报(内部) 2:总提交人(内部) 3: 总提交人(外部)
    private static final String IN_NOTCOLLECTCNT_DATATYPE = "1";
    private static final String IN_COLLECTCNT_DATATYPE = "2";
    private static final String EX_COLLECTCNT_DATATYPE  = "3";

    private static final String BASE_URL = "http://fangkong.hfmri.net:18080";
    /**
     * 查询疫情防控信息收集
     *
     * @param id 疫情防控信息收集主键
     * @return 疫情防控信息收集
     */
    @Override
    public YqInfoCollect selectYqInfoCollectById(Long id)
    {
        return yqInfoCollectMapper.selectYqInfoCollectById(id);
    }

    /**
     * 查询疫情防控信息收集列表
     *
     * @param yqInfoCollect 疫情防控信息收集
     * @return 疫情防控信息收集
     */
    @Override
    public List<YqInfoCollect> selectYqInfoCollectList(YqInfoCollect yqInfoCollect)
    {
        return yqInfoCollectMapper.selectYqInfoCollectList(yqInfoCollect);
    }

    @Override
    public List<YqInfoCollect> selectYqInfoCollectListAduit(YqInfoCollect yqInfoCollect) {
        return yqInfoCollectMapper.selectYqInfoCollectListAduit(yqInfoCollect);
    }

    @Override
    public int checkDept(String userid) {
        Long aLong = yqInfoCollectMapper.selectUserDept(userid);
        if(aLong == null){
            return -1;
        } else {
            return 1;
        }
    }

    @Override
    public String getFillDept(String userid) {
        String detName = yqInfoCollectMapper.selectUserDeptName(userid);
        return detName;
    }

    @Override
    public int insertYqInfo(YqInfoCollect yqInfoCollect) {
        yqInfoCollect.setCreateTime(DateUtils.getNowDate());
        String belongDate= FORMAT_DATE.format(LocalDateTime.now());
        yqInfoCollect.setBelongDate(belongDate);

        // 查询用户信息
        if("00".equals(yqInfoCollect.getUserType())) {//内部员工
        	 WxCpUser wxCpUser = IWxCpUserService.selectWxCpUserByUserId(yqInfoCollect.getUserId());
             yqInfoCollect.setUserName(wxCpUser.getUserName());
             // 查询所属填报部门信息
             // 如果未查询到填报部门，提醒用户先进行填报部门维护，再提交填报信息,返回-1
             Long aLong = yqInfoCollectMapper.selectUserDept(yqInfoCollect.getUserId());

             if(aLong == null){
                 return -1;
             } else {
                 yqInfoCollect.setDeptId(aLong);

             }
        }
        return yqInfoCollectMapper.insertYqInfoCollect(yqInfoCollect);

    }

    /**
     * 新增疫情防控信息收集
     *
     * @param yqInfoCollect 疫情防控信息收集
     * @return 结果
     */
    @Override
    public int insertYqInfoCollect(YqInfoCollect yqInfoCollect,String userId)
    {
        yqInfoCollect.setCreateTime(DateUtils.getNowDate());
        String belongDate= FORMAT_DATE.format(LocalDateTime.now());
        yqInfoCollect.setBelongDate(belongDate);
        yqInfoCollect.setUserType("00");
        yqInfoCollect.setUserId(userId);
        return yqInfoCollectMapper.insertYqInfoCollect(yqInfoCollect);
    }

    /**
     * 修改疫情防控信息收集
     *
     * @param yqInfoCollect 疫情防控信息收集
     * @return 结果
     */
    @Override
    public int updateYqInfoCollect(YqInfoCollect yqInfoCollect)
    {
        yqInfoCollect.setUpdateTime(DateUtils.getNowDate());
        return yqInfoCollectMapper.updateYqInfoCollect(yqInfoCollect);
    }

    /**
     * 批量删除疫情防控信息收集
     *
     * @param ids 需要删除的疫情防控信息收集主键
     * @return 结果
     */
    @Override
    public int deleteYqInfoCollectByIds(String ids)
    {
        return yqInfoCollectMapper.deleteYqInfoCollectByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除疫情防控信息收集信息
     *
     * @param id 疫情防控信息收集主键
     * @return 结果
     */
    @Override
    public int deleteYqInfoCollectById(Long id)
    {
        return yqInfoCollectMapper.deleteYqInfoCollectById(id);
    }

    /***
     * 审核选中内容
     * @param ids
     * @return
     */
    @Override
    public int aduitYqInfoCollectByIds(String ids) {
        return yqInfoCollectMapper.aduitYqInfoCollectByIds(Convert.toStrArray(ids));
    }

    /**
     * 审核所有查询列表
     * @param yqInfoCollect
     * @return
     */
    @Override
    public int aduitInfosAllSelect(YqInfoCollect yqInfoCollect) {
        return yqInfoCollectMapper.aduitInfosAllSelect(yqInfoCollect);
    }


    /**
     * 递归子查询
     * @param deptId
     * @param deptIdInfoList
     * @param childDeptIdList
     */
    public void getChildrens(Long deptId,List<DeptIdInfo> deptIdInfoList, List<Long> childDeptIdList){
        if (CollUtil.isNotEmpty(deptIdInfoList)) {
            for (DeptIdInfo item: deptIdInfoList) {
                if (item.getDeptParentId().equals(deptId)) {
                    childDeptIdList.add(item.getDeptId());
                    getChildrens(item.getDeptId(),deptIdInfoList, childDeptIdList);
                }
            }
        }
    }

    @Override
    public List<DeptStaticData> getLeaderviewListByDeptIds(String belongDate, String flag, List<EpidemicControlDept> list){
        List<DeptStaticData> listData = new ArrayList<>();
        //每个部门id所对应的所有子部门id列表
        List<Long> deptIds = list.stream().map(item -> item.getDeptId()).collect(Collectors.toList());
        Map<Long, List<Long>> deptTreeMap = new HashMap<>();
        List<Long> childDeptIds = new ArrayList<>();
        if (CollUtil.isNotEmpty(deptIds)) {
            for (Long deptId: deptIds) {
                deptTreeMap.put(deptId, getDeptTreeIds(flag, deptId));
                childDeptIds.addAll(getDeptTreeIds(flag, deptId));
            }
        }
        if (CollUtil.isNotEmpty(childDeptIds)) {
            //总人数
            List<DeptUserCntDTO> deptUserCntList =epidemicUserDeptBashService.selectCountUserNewGroupDeptId(childDeptIds);
            Map<Long, Integer> deptUserCntMap = null;
            if (CollUtil.isNotEmpty(deptUserCntList)) {
                deptUserCntMap = deptUserCntList.stream().collect(Collectors.toMap(DeptUserCntDTO::getDeptId, DeptUserCntDTO::getCnt));
            }
            //外部人员的总填报信息
            List<YgCollectDTO> ygCollectDTOList = yqInfoCollectMapper.getYgCollectDTOList(belongDate, childDeptIds);

            if (CollUtil.isNotEmpty(ygCollectDTOList)) {
                //总填报数(过滤掉被拒绝/审核不通过的)
                Map<Long, Long> collectcntMap= ygCollectDTOList.stream().filter(item -> !"2".equals(item.getAduitStatus())).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                //已审核数(只包括审核通过的)
                Map<Long, Long> aduitcntMap =  ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus())).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                //已审核总异常数量xcm_is_leave ='N' or akm_status>0 or hs_result =1 or tw_is_normal='N'
                Map<Long, Long> expcntMap =  ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus()) && ("N".equals(item.getXcmIsLeave()) || !"0".equals(item.getAkmStatus()) || "1".equals(item.getHsResult()) || "N".equals(item.getTwIsNormal()))).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));

                //已审核红码数量
                Map<Long, Long> redcntMap = ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus()) && "2".equals(item.getAkmStatus())).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                //已审核黄码数量
                Map<Long, Long> yellowcntMap = ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus()) && "1".equals(item.getAkmStatus())).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                //已审核行程异常数量
                Map<Long, Long> tripcntMap =  ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus()) && "N".equals(item.getXcmIsLeave())).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                //已审核体温异常数量
                Map<Long, Long> tempcntMap = ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus()) && "N".equals(item.getTwIsNormal())).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                //已审核核算异常数量
                Map<Long, Long> yangcntMap = ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus()) &&  "1".equals(item.getHsResult())).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                //未审核总异常数量
                Map<Long, Long> notAduitexpcntMap =  ygCollectDTOList.stream().filter(item -> !"1".equals(item.getAduitStatus()) && ("N".equals(item.getXcmIsLeave()) || !"0".equals(item.getAkmStatus()) || "1".equals(item.getHsResult()) || "N".equals(item.getTwIsNormal()))).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                //未审核红码数量
                Map<Long, Long> notAduitredcntMap =  ygCollectDTOList.stream().filter(item -> !"1".equals(item.getAduitStatus()) && "2".equals(item.getAkmStatus())).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                //未审核黄码数量
                Map<Long, Long> notAduityellowcntMap = ygCollectDTOList.stream().filter(item -> !"1".equals(item.getAduitStatus()) && "1".equals(item.getAkmStatus())).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                //未审核行程异常数量
                Map<Long, Long> notAduittripcntMap = ygCollectDTOList.stream().filter(item -> !"1".equals(item.getAduitStatus()) && "N".equals(item.getXcmIsLeave())).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                //未审核体温异常数量
                Map<Long, Long> notAduittempcntMap = ygCollectDTOList.stream().filter(item -> !"1".equals(item.getAduitStatus()) && "N".equals(item.getTwIsNormal())).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                //未审核核算异常数量
                Map<Long, Long> notAduityangcntMap = ygCollectDTOList.stream().filter(item -> !"1".equals(item.getAduitStatus()) &&  "1".equals(item.getHsResult())).collect(Collectors.groupingBy(m->m.getDeptId(), Collectors.counting()));
                for (EpidemicControlDept dept : list) {
                    //当前部门id
                    Long curDeptId = dept.getDeptId();
                    //当前部门id所对应的子部门包括自己的id列表
                    List<Long> childTreeDeptIds = deptTreeMap.get(curDeptId);
                    int usercnt = 0, collectcnt = 0, notcollectcnt = 0, aduitcnt = 0, notAduitcnt = 0, expcnt=0;
                    int nomalcnt = 0, redcnt = 0, yellowcnt = 0, tripcnt=0, tempcnt = 0, yangcnt = 0;
                    int notAduitexpcnt =0, notAduitnomalcnt=0, notAduitredcnt =0,notAduityellowcnt = 0,notAduittripcnt =  0,notAduittempcnt= 0, notAduityangcnt = 0;
                    if (CollUtil.isNotEmpty(childTreeDeptIds)) {
                        for (Long cur: childTreeDeptIds) {
                            if (ObjectUtil.isNotNull(deptUserCntMap) && ObjectUtil.isNotNull(deptUserCntMap.get(cur))) {
                                usercnt += deptUserCntMap.get(cur);
                            }
                            if (ObjectUtil.isNotNull(collectcntMap) && ObjectUtil.isNotNull(collectcntMap.get(cur))) {
                                collectcnt += collectcntMap.get(cur);
                            }
                            //未填报数
                            notcollectcnt=(usercnt-collectcnt) >= 0 ? (usercnt-collectcnt) : 0;

                            if (ObjectUtil.isNotNull(aduitcntMap) && ObjectUtil.isNotNull(aduitcntMap.get(cur))) {
                                aduitcnt += aduitcntMap.get(cur);
                            }
                            //未审核数
                            notAduitcnt= (collectcnt-aduitcnt) >= 0 ? (collectcnt-aduitcnt) : 0;
                            if (ObjectUtil.isNotNull(expcntMap) && ObjectUtil.isNotNull(expcntMap.get(cur))) {
                                expcnt += expcntMap.get(cur);
                            }
                            //已审核总正常数量
                            nomalcnt= (aduitcnt-expcnt) >= 0 ? (aduitcnt-expcnt): 0;
                            if (ObjectUtil.isNotNull(redcntMap) && ObjectUtil.isNotNull(redcntMap.get(cur))) {
                                redcnt += redcntMap.get(cur);
                            }
                            if (ObjectUtil.isNotNull(yellowcntMap) && ObjectUtil.isNotNull(yellowcntMap.get(cur))) {
                                yellowcnt += yellowcntMap.get(cur);
                            }
                            if (ObjectUtil.isNotNull(tripcntMap) && ObjectUtil.isNotNull(tripcntMap.get(cur))) {
                                tripcnt += tripcntMap.get(cur);
                            }
                            if (ObjectUtil.isNotNull(tempcntMap) && ObjectUtil.isNotNull(tempcntMap.get(cur))) {
                                tempcnt += tempcntMap.get(cur);
                            }
                            if (ObjectUtil.isNotNull(yangcntMap) && ObjectUtil.isNotNull(yangcntMap.get(cur))) {
                                yangcnt += yangcntMap.get(cur);
                            }

                            if (ObjectUtil.isNotNull(notAduitexpcntMap) && ObjectUtil.isNotNull(notAduitexpcntMap.get(cur))) {
                                notAduitexpcnt += notAduitexpcntMap.get(cur);
                            }
                            //未审核总正常数量
                            notAduitnomalcnt = (notAduitcnt-notAduitexpcnt) >= 0 ? (notAduitcnt-notAduitexpcnt): 0;
                            if (ObjectUtil.isNotNull(notAduitredcntMap) && ObjectUtil.isNotNull(notAduitredcntMap.get(cur))) {
                                notAduitredcnt += notAduitredcntMap.get(cur);
                            }
                            if (ObjectUtil.isNotNull(notAduityellowcntMap) && ObjectUtil.isNotNull(notAduityellowcntMap.get(cur))) {
                                notAduityellowcnt += notAduityellowcntMap.get(cur);
                            }
                            if (ObjectUtil.isNotNull(notAduittripcntMap) && ObjectUtil.isNotNull(notAduittripcntMap.get(cur))) {
                                notAduittripcnt += notAduittripcntMap.get(cur);
                            }
                            if (ObjectUtil.isNotNull(notAduittempcntMap) && ObjectUtil.isNotNull(notAduittempcntMap.get(cur))) {
                                notAduittempcnt += notAduittempcntMap.get(cur);
                            }
                            if (ObjectUtil.isNotNull(notAduityangcntMap) && ObjectUtil.isNotNull(notAduityangcntMap.get(cur))) {
                                notAduityangcnt += notAduityangcntMap.get(cur);
                            }
                        }
                    }
                    Map<String,Integer> view = new HashMap<>();
                    view.put("usercnt", usercnt);
                    view.put("notcollectcnt", notcollectcnt);
                    view.put("collectcnt", collectcnt);
                    view.put("notAduitcnt", notAduitcnt);
                    view.put("aduitcnt", aduitcnt);
                    view.put("nomalcnt", nomalcnt);
                    view.put("redcnt", redcnt);
                    view.put("yellowcnt", yellowcnt);
                    view.put("tripcnt", tripcnt);
                    view.put("tempcnt", tempcnt);
                    view.put("yangcnt", yangcnt);
                    view.put("notAduitnomalcnt", notAduitnomalcnt);
                    view.put("notAduitredcnt", notAduitredcnt);
                    view.put("notAduityellowcnt", notAduityellowcnt);
                    view.put("notAduittripcnt", notAduittripcnt);
                    view.put("notAduittempcnt", notAduittempcnt);
                    view.put("notAduityangcnt", notAduityangcnt);
                    listData.add(DeptStaticData.builder().deptId(dept.getDeptId()).deptName(dept.getDeptName()).staticDataMap(view).build());
                }
            }
        }
        return listData;
    }

    /**
     * 获取当前部门所关联的所有子部门ids
     * @param flag
     * @param deptId
     */
    private List<Long> getDeptTreeIds(String flag, Long deptId) {
        List<Long> childDeptIdList = new ArrayList<>();
        childDeptIdList.add(deptId);
        List<DeptIdInfo> deptIdInfoList = yqInfoCollectMapper.getDeptIdInfoList(flag);
        getChildrens(deptId, deptIdInfoList, childDeptIdList);
        return childDeptIdList;
    }

    /**
     * 获取领导视图统计数据的新方法
     * @param belongDate
     * @param deptId
     * @param flag
     * @return
     */
    @Override
    public Map<String, Integer> getLeaderviewNew(String belongDate, Long deptId, String flag) {
        //总人数
        int usercnt = 0, collectcnt = 0, notcollectcnt = 0, aduitcnt = 0, notAduitcnt = 0, expcnt;
        int nomalcnt = 0, redcnt = 0, yellowcnt = 0, tripcnt=0, tempcnt = 0, yangcnt = 0;
        int notAduitexpcnt, notAduitnomalcnt=0, notAduitredcnt =0,notAduityellowcnt = 0,notAduittripcnt =  0,notAduittempcnt= 0, notAduityangcnt = 0;
        //根据当前部门id,递归查询其下所有的子部门id
        List<Long> childDeptIdList = getDeptTreeIds(flag, deptId);
        if (CollUtil.isNotEmpty(childDeptIdList)) {
            //总人数
            usercnt =epidemicUserDeptBashService.selectCountUserNew(childDeptIdList);
            //外部人员的总填报信息
            List<YgCollectDTO> ygCollectDTOList = yqInfoCollectMapper.getYgCollectDTOList(belongDate, childDeptIdList);
            if (CollUtil.isNotEmpty(ygCollectDTOList)) {
                //总填报数(过滤掉被拒绝/审核不通过的)
                collectcnt= cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> !"2".equals(item.getAduitStatus())).count());
                //未填报数
                notcollectcnt=(usercnt-collectcnt) >= 0 ? (usercnt-collectcnt) : 0;
                //已审核数(只包括审核通过的)
                aduitcnt=  cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus())).count());
                //未审核数
                notAduitcnt= (collectcnt-aduitcnt) >= 0 ? (collectcnt-aduitcnt) : 0;
                //已审核总异常数量xcm_is_leave ='N' or akm_status>0 or hs_result =1 or tw_is_normal='N'
                expcnt =  cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus()) && ("N".equals(item.getXcmIsLeave()) ||"S".equals(item.getXcmIsLeave()) || !"0".equals(item.getAkmStatus()) || "1".equals(item.getHsResult()) || "N".equals(item.getTwIsNormal()))).count());
                //已审核总正常数量
                nomalcnt= (aduitcnt-expcnt) >= 0 ? (aduitcnt-expcnt): 0;
                //已审核红码数量
                redcnt = cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus()) && "2".equals(item.getAkmStatus())).count());
                //已审核黄码数量
                yellowcnt = cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus()) && "1".equals(item.getAkmStatus())).count());
                //已审核行程异常数量
                tripcnt =  cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus()) && ("N".equals(item.getXcmIsLeave()) || "S".equals(item.getXcmIsLeave()))).count());
                //已审核体温异常数量
                tempcnt= cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus()) && "N".equals(item.getTwIsNormal())).count());
                //已审核核算异常数量
                yangcnt = cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> "1".equals(item.getAduitStatus()) &&  "1".equals(item.getHsResult())).count());

                //未审核总异常数量
                notAduitexpcnt =  cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> !"1".equals(item.getAduitStatus()) && ("N".equals(item.getXcmIsLeave()) ||"S".equals(item.getXcmIsLeave())  || !"0".equals(item.getAkmStatus()) || "1".equals(item.getHsResult()) || "N".equals(item.getTwIsNormal()))).count());
                //未审核总正常数量
                notAduitnomalcnt=(notAduitcnt-notAduitexpcnt) >= 0 ? (notAduitcnt-notAduitexpcnt): 0;
                //未审核红码数量
                notAduitredcnt =  cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> !"1".equals(item.getAduitStatus()) && "2".equals(item.getAkmStatus())).count());
                //未审核黄码数量
                notAduityellowcnt =  cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> !"1".equals(item.getAduitStatus()) && "1".equals(item.getAkmStatus())).count());
                //未审核行程异常数量
                notAduittripcnt =   cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> !"1".equals(item.getAduitStatus()) && ("N".equals(item.getXcmIsLeave()) ||"S".equals(item.getXcmIsLeave()))).count());
                //未审核体温异常数量
                notAduittempcnt= cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> !"1".equals(item.getAduitStatus()) && "N".equals(item.getTwIsNormal())).count());
                //未审核核算异常数量
                notAduityangcnt = cn.hutool.core.convert.Convert.toInt(ygCollectDTOList.stream().filter(item -> !"1".equals(item.getAduitStatus()) &&  "1".equals(item.getHsResult())).count());
            }
        }
        Map<String,Integer>  view = new HashMap<>();
        view.put("usercnt", usercnt);
        view.put("notcollectcnt", notcollectcnt);
        view.put("collectcnt", collectcnt);
        view.put("notAduitcnt", notAduitcnt);
        view.put("aduitcnt", aduitcnt);
        view.put("nomalcnt", nomalcnt);
        view.put("redcnt", redcnt);
        view.put("yellowcnt", yellowcnt);
        view.put("tripcnt", tripcnt);
        view.put("tempcnt", tempcnt);
        view.put("yangcnt", yangcnt);
        view.put("notAduitnomalcnt", notAduitnomalcnt);
        view.put("notAduitredcnt", notAduitredcnt);
        view.put("notAduityellowcnt", notAduityellowcnt);
        view.put("notAduittripcnt", notAduittripcnt);
        view.put("notAduittempcnt", notAduittempcnt);
        view.put("notAduityangcnt", notAduityangcnt);
        logger.info("view:"+view);
        return view;
    }

    @Override
    public Map<String,Integer> getLeaderview(String belongDate,Long deptId, String flag) {
        //总人数
        int usercnt=epidemicUserDeptBashService.selectCountUser(deptId, flag);
        //总填报数(过滤掉被拒绝/审核不通过的)
        int collectcnt=yqInfoCollectMapper.getCollectCount(belongDate,deptId, flag);
        //未填报数
        int notcollectcnt=(usercnt-collectcnt) >= 0 ? (usercnt-collectcnt) : 0;
        //已审核数(只包括审核通过的)
        int aduitcnt=  yqInfoCollectMapper.getSubmitCount(belongDate,deptId, flag);
        //未审核数
        int notAduitcnt= (collectcnt-aduitcnt) >= 0 ? (collectcnt-aduitcnt) : 0;
//        已审核总异常数量
        int expcnt =  yqInfoCollectMapper.getExpCount(belongDate,aduitComplete,deptId, flag);
//        已审核总正常数量
        int nomalcnt= (aduitcnt-expcnt) >= 0 ? (aduitcnt-expcnt): 0;
//        已审核红码数量
        int redcnt = yqInfoCollectMapper.getRedCount(belongDate,aduitComplete,deptId, flag);
//        已审核黄码数量
         int yellowcnt = yqInfoCollectMapper.getYellowCount(belongDate,aduitComplete,deptId, flag);
//        已审核行程异常数量
         int tripcnt =  yqInfoCollectMapper.getTripCount(belongDate,aduitComplete,deptId, flag);
//        已审核体温异常数量
         int tempcnt= yqInfoCollectMapper.getTempCount(belongDate,aduitComplete,deptId, flag);
//        已审核核算异常数量
         int yangcnt =yqInfoCollectMapper.getYangCount(belongDate,aduitComplete,deptId, flag);

//        未审核总异常数量
        int notAduitexpcnt =  yqInfoCollectMapper.getExpCount(belongDate,notaduit,deptId, flag);
//        未审核总正常数量
        int notAduitnomalcnt=(notAduitcnt-notAduitexpcnt) >= 0 ? (notAduitcnt-notAduitexpcnt): 0;
//        未审核红码数量
        int notAduitredcnt =  yqInfoCollectMapper.getRedCount(belongDate,notaduit,deptId, flag);
//        未审核黄码数量
        int notAduityellowcnt =  yqInfoCollectMapper.getYellowCount(belongDate,notaduit,deptId, flag);
//        未审核行程异常数量
        int notAduittripcnt =  yqInfoCollectMapper.getTripCount(belongDate,notaduit,deptId, flag);
//        未审核体温异常数量
        int notAduittempcnt= yqInfoCollectMapper.getTempCount(belongDate,notaduit,deptId, flag);
//        未审核核算异常数量
        int notAduityangcnt = yqInfoCollectMapper.getYangCount(belongDate,notaduit,deptId, flag);
         Map<String,Integer>  view = new HashMap<>();
        view.put("usercnt", usercnt);
        view.put("notcollectcnt", notcollectcnt);
        view.put("collectcnt", collectcnt);
        view.put("notAduitcnt", notAduitcnt);
         view.put("aduitcnt", aduitcnt);
         view.put("nomalcnt", nomalcnt);
         view.put("redcnt", redcnt);
        view.put("yellowcnt", yellowcnt);
        view.put("tripcnt", tripcnt);
        view.put("tempcnt", tempcnt);
        view.put("yangcnt", yangcnt);
        view.put("notAduitnomalcnt", notAduitnomalcnt);
        view.put("notAduitredcnt", notAduitredcnt);
        view.put("notAduityellowcnt", notAduityellowcnt);
        view.put("notAduittripcnt", notAduittripcnt);
        view.put("notAduittempcnt", notAduittempcnt);
        view.put("notAduityangcnt", notAduityangcnt);
        logger.info("view:"+view);
        return view;
    }

    @Override
    public List<Long> checkAduit(String userid) {
        return yqInfoCollectMapper.checkAduit(userid);
    }

    @Override
    public List<AuditUserDTO> getAuditUserList(String userId, String deptId, String date) {
        return yqInfoCollectMapper.getAuditUserList(userId, deptId, date);
    }

    @Override
    public List<String> getAuditUserIdList(String userId, String deptId, String date) {
        return yqInfoCollectMapper.getAuditUserIdList(userId, deptId, date);
    }

    @Override
    public List<String> getUserIdListByDeptIds(String userId, String deptId) {
        return yqInfoCollectMapper.getUserIdListByDeptIds(userId, deptId);
    }

    @Override
    public List<AuditUserDTO> getUnsubmitUserList(List<String> userIdList) {
        return yqInfoCollectMapper.getUnsubmitUserList(userIdList);
    }

    @Override
    public YqInfoCollect getYqInfoCollectByUserId(String userId, String date) {
        return yqInfoCollectMapper.getYqInfoCollectByUserId(userId,date);
    }

    /**
     * 根据用户userId获取审批人userId
     * @param userId
     * @return
     */
    @Override
    public List<String> getAuditUserByUserId(String userId){
        return yqInfoCollectMapper.getAuditUserByUserId(userId);
    }

    @Override
    public List<AuditUserDTO> getUserInfoListByDeptIds(String userId, String deptId) {
        return yqInfoCollectMapper.getUserInfoListByDeptIds(userId, deptId);
    }

    @Override
    public int deleteEpidemicUserDeptBashByUserId(String userId) {
        return yqInfoCollectMapper.deleteEpidemicUserDeptBashByUserId(userId);
    }

    @Override
    public List<AuditUserDTO> getDeptListByUserId(String userId) {
        return yqInfoCollectMapper.getDeptListByUserId(userId);
    }

    @Override
    public String selectDeptNameByDeptId(String deptId) {
        return yqInfoCollectMapper.selectDeptNameByDeptId(deptId);
    }

    @Override
    public AuditUserDTO selectUserInfoFromEpidemicUserDeptBash(String userId) {
        return yqInfoCollectMapper.selectUserInfoFromEpidemicUserDeptBash(userId);
    }

    @Override
    public AuditUserDTO selectUserInfoFromWxCpUser(String userId) {
        return yqInfoCollectMapper.selectUserInfoFromWxCpUser(userId);
    }

    @Override
    public String selectManagerByDeptId(Long deptId) {
        return yqInfoCollectMapper.selectManagerByDeptId(deptId);
    }

    @Override
    public List<YqInfoCollect> selectYqInfoCollectByPhoneNumber(String phonenumber, String belongDate) {
        return yqInfoCollectMapper.selectYqInfoCollectByPhoneNumber(phonenumber,  belongDate);
    }

    @Override
    public List<DeptTreeViewItem> getUserDeptListByPermType(String userId, Integer permissionType) {
        return yqInfoCollectMapper.getUserDeptListByPermType(userId,  permissionType);
    }

    @Override
    public List<DeptTreeViewItem> getAllDeptListFromControlDept() {
        return yqInfoCollectMapper.getAllDeptListFromControlDept();
    }

    @Override
    public void downExcelFile(Long deptId, String dataType,String belongDate, HttpServletResponse response) {
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFCellStyle style = wb.createCellStyle();
        String deptName = yqInfoCollectMapper.getDeptNameByDeptId(deptId);
        //字体样式
        XSSFFont fontStyle = wb.createFont();
        fontStyle.setFontName("微软雅黑");
        fontStyle.setFontHeightInPoints((short) 12);
        style.setFont(fontStyle);
        style.setAlignment(HorizontalAlignment.CENTER);
        if (IN_NOTCOLLECTCNT_DATATYPE.equalsIgnoreCase(dataType)) {// 1:未填报(内部)
            exportExcelFileForInNotcollectcnt(response, wb, style, deptId, deptName,belongDate);
        } else if (IN_COLLECTCNT_DATATYPE.equalsIgnoreCase(dataType)) {//2:总提交人(内部)
            exportExcelFileForInCollectcnt(response, wb, style, deptId, deptName,belongDate);
        } else if (EX_COLLECTCNT_DATATYPE.equalsIgnoreCase(dataType)) {// 3: 总提交人(外部)
            exportExcelFileForExcollectcnt(response, wb, style, deptId, deptName,belongDate);
        }
    }

    /**
     * 1:未填报(内部)
     * @param response
     * @param wb
     * @param style
     */
    private void exportExcelFileForInNotcollectcnt(HttpServletResponse response, XSSFWorkbook wb, XSSFCellStyle style, Long deptId, String deptName, String belongDate) {
        //总人数
        List<String> userIds=epidemicUserDeptBashService.selectCountUserIds(deptId, "N");
        //总填报数(过滤掉被拒绝/审核不通过的)
        List<String> collectUserIds=yqInfoCollectMapper.getCollectUserIds(belongDate,deptId, "N");
        //未填报数
        List<String> notcollectUserIds = CollectionUtil.subtractToList(userIds, collectUserIds);
        if(CollUtil.isNotEmpty(notcollectUserIds)){
            //根据notcollectUserIds用户ids从epidemic_user_dept_bash查询当前所有用户的信息
            List<String> headers = Arrays.asList("序号", "工号/手机号", "姓名", "部门");
            XSSFSheet sheet = wb.createSheet();
            wb.setSheetName(0, deptName);
            MyExcelUtil.setHeaders(wb, sheet, headers);
            List<AuditUserDTO> userList = yqInfoCollectMapper.selectExportUserInfoList(notcollectUserIds);
            if (CollUtil.isNotEmpty(userList)) {
                for (int i = 0, size = userList.size(); i < size; i++) {
                    AuditUserDTO dto = userList.get(i);
                    XSSFRow hssfRow = sheet.createRow(i+1);
                    //序号
                    XSSFCell hssfCell0 = hssfRow.createCell(0);
                    hssfCell0.setCellStyle(style);
                    hssfCell0.setCellValue(i+1);
                    //工号/手机号
                    XSSFCell hssfCell1 = hssfRow.createCell(1);
                    hssfCell1.setCellStyle(style);
                    hssfCell1.setCellValue(StrUtil.isEmpty(dto.getUserId())?"":dto.getUserId());
                    //姓名
                    XSSFCell hssfCell2 = hssfRow.createCell(2);
                    hssfCell2.setCellStyle(style);
                    hssfCell2.setCellValue(StrUtil.isEmpty(dto.getUserName())?"":dto.getUserName());
                    //部门
                    XSSFCell hssfCell3 = hssfRow.createCell(3);
                    hssfCell3.setCellStyle(style);
                    hssfCell3.setCellValue(StrUtil.isEmpty(dto.getDeptName())?"":dto.getDeptName());
                }
            }
        }
        MyExcelUtil.commonExcelDownload(response, deptName+ "(未填报)-"+DateUtil.today() +".xlsx", wb);
    }

    /**
     * 2:总提交人(内部)
     * @param response
     * @param wb
     * @param style
     */
    private void exportExcelFileForInCollectcnt(HttpServletResponse response, XSSFWorkbook wb, XSSFCellStyle style, Long deptId, String deptName, String belongDate) {
        //总填报数(过滤掉被拒绝/审核不通过的)
        List<String> collectUserIds=yqInfoCollectMapper.getCollectUserIds(belongDate,deptId, "N");
        if (CollUtil.isNotEmpty(collectUserIds)) {
            //根据用户ids从yq_info_collect表中查询用户的填报信息,审核状态为未审核/审核通过
            List<YqInfoCollectDTO> yqInfoCollectDTOList = yqInfoCollectMapper.selectYqInfoCollectListByUserIds(belongDate, collectUserIds);
            //设置Excel内容数据
            setExcelBody(wb, style, deptName, yqInfoCollectDTOList);
        }
        MyExcelUtil.commonExcelDownload(response, deptName+ "(总提交)-"+DateUtil.today() +".xlsx", wb);
    }

    /**
     * 设置Excel数据内容
     * @param wb
     * @param style
     * @param deptName
     * @param yqInfoCollectDTOList
     */
    private void setExcelBody(XSSFWorkbook wb, XSSFCellStyle style, String deptName, List<YqInfoCollectDTO> yqInfoCollectDTOList) {
        if (CollUtil.isNotEmpty(yqInfoCollectDTOList)) {
            List<String> headers = Arrays.asList("序号", "工号", "姓名", "部门", "手机号", "安康码状态", "安康码截图", "核酸检测时间",
                    "两日内核酸检测结果", "核酸检测报告截图", "行程码14天是否未离肥", "行程码截图", "体温是否正常", "备注", "审核状态", "提交时间");
            XSSFSheet sheet = wb.createSheet();
            wb.setSheetName(0, deptName+"(总提交)");
            //设置表头
            XSSFRow rowFirst = sheet.createRow(0);
            for (int i = 0; i < headers.size(); i++) {
                XSSFCell cell = rowFirst.createCell(i);
                sheet.setColumnWidth(i, 4000);
                cell.setCellStyle(style);
                cell.setCellValue(headers.get(i));
            }
            //设置表内容
            for (int i = 0, size = yqInfoCollectDTOList.size(); i < size; i++) {
                YqInfoCollectDTO dto = yqInfoCollectDTOList.get(i);
                XSSFRow hssfRow = sheet.createRow(i+1);
                //序号
                XSSFCell hssfCell0 = hssfRow.createCell(0);
                hssfCell0.setCellStyle(style);
                hssfCell0.setCellValue(i+1);
                //工号
                XSSFCell hssfCell1 = hssfRow.createCell(1);
                hssfCell1.setCellStyle(style);
                hssfCell1.setCellValue(StrUtil.isEmpty(dto.getUserId())?"":dto.getUserId());
                //姓名
                XSSFCell hssfCell2 = hssfRow.createCell(2);
                hssfCell2.setCellStyle(style);
                hssfCell2.setCellValue(StrUtil.isEmpty(dto.getUserName())?"":dto.getUserName());
                //部门
                XSSFCell hssfCell3 = hssfRow.createCell(3);
                hssfCell3.setCellStyle(style);
                hssfCell3.setCellValue(StrUtil.isEmpty(dto.getDeptName())?"":dto.getDeptName());
                //手机号
                XSSFCell hssfCell4 = hssfRow.createCell(4);
                hssfCell4.setCellStyle(style);
                hssfCell4.setCellValue(StrUtil.isEmpty(dto.getPhonenumber())?"":dto.getPhonenumber());
                //安康码状态
                XSSFCell hssfCell5 = hssfRow.createCell(5);
                hssfCell5.setCellStyle(style);
                //0绿码 1黄码 2红码
                String akmStatus;
                if ("0".equalsIgnoreCase(dto.getAkmStatus())) {
                    akmStatus = "绿码";
                } else if ("1".equalsIgnoreCase(dto.getAkmStatus())) {
                    akmStatus = "黄码";
                } else if ("2".equalsIgnoreCase(dto.getAkmStatus())) {
                    akmStatus = "红码";
                } else {
                    akmStatus = "";
                }
                hssfCell5.setCellValue(akmStatus);
                //安康码截图
                XSSFCell hssfCell6 = hssfRow.createCell(6);
                hssfCell6.setCellStyle(style);
                hssfCell6.setCellValue(StrUtil.isEmpty(dto.getAkmPath())? "":BASE_URL+dto.getAkmPath());
//                if (StrUtil.isEmpty(dto.getAkmPath())) {
//                    hssfCell6.setCellValue("");
//                } else {
//                    setPicToCell(wb, sheet,dto.getAkmPath(),i+1, 6,1, 1);
//                }
                //核酸检测时间
                XSSFCell hssfCell7 = hssfRow.createCell(7);
                hssfCell7.setCellStyle(style);
                hssfCell7.setCellValue(ObjectUtil.isNull(dto.getHsTime())?"":DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, dto.getHsTime()));
                //两日内核酸检测结果
                XSSFCell hssfCell8 = hssfRow.createCell(8);
                hssfCell8.setCellStyle(style);
                //0阴性 1阳性
                String hsResult;
                if ("0".equalsIgnoreCase(dto.getHsResult())) {
                    hsResult = "阴性";
                } else if ("1".equalsIgnoreCase(dto.getHsResult())) {
                    hsResult = "阳性";
                } else {
                    hsResult = "";
                }
                hssfCell8.setCellValue(hsResult);
                //核酸检测报告截图
                XSSFCell hssfCell9 = hssfRow.createCell(9);
                hssfCell9.setCellStyle(style);
                hssfCell9.setCellValue(StrUtil.isEmpty(dto.getHsPath())? "":BASE_URL+dto.getHsPath());
//                if (StrUtil.isEmpty(dto.getHsPath())) {
//                    hssfCell9.setCellValue("");
//                } else {
//                    setPicToCell(wb, sheet,dto.getHsPath(),i+1, 9,1, 1);
//                }
                //行程码14天是否未离肥
                XSSFCell hssfCell10 = hssfRow.createCell(10);
                hssfCell10.setCellStyle(style);
                //N否 Y是
                String xcmIsLeave;
                if ("Y".equalsIgnoreCase(dto.getXcmIsLeave())) {
                    xcmIsLeave = "未离肥";
                } else if ("N".equalsIgnoreCase(dto.getXcmIsLeave())) {
                    xcmIsLeave = "24小时内有离肥记录";
                } else {
                    xcmIsLeave = "";
                }
                hssfCell10.setCellValue(xcmIsLeave);
                //行程码截图
                XSSFCell hssfCell11 = hssfRow.createCell(11);
                hssfCell11.setCellStyle(style);
                hssfCell11.setCellValue(StrUtil.isEmpty(dto.getXcmPath())? "":BASE_URL+dto.getXcmPath());
//                if (StrUtil.isEmpty(dto.getXcmPath())) {
//                    hssfCell11.setCellValue("");
//                } else {
//                    setPicToCell(wb, sheet,dto.getXcmPath(),i+1, 11,1, 1);
//                }
                //体温是否正常
                XSSFCell hssfCell12 = hssfRow.createCell(12);
                hssfCell12.setCellStyle(style);
                //N否 Y是
                String twIsNormal;
                if ("Y".equalsIgnoreCase(dto.getTwIsNormal())) {
                    twIsNormal = "是";
                } else if ("N".equalsIgnoreCase(dto.getTwIsNormal())) {
                    twIsNormal = "否";
                } else {
                    twIsNormal = "";
                }
                hssfCell12.setCellValue(twIsNormal);
                //体温异常原因
                XSSFCell hssfCell13 = hssfRow.createCell(13);
                hssfCell13.setCellStyle(style);
                hssfCell13.setCellValue(StrUtil.isEmpty(dto.getTwYcReason())?"":dto.getTwYcReason());
                //审核状态
                XSSFCell hssfCell14 = hssfRow.createCell(14);
                hssfCell14.setCellStyle(style);
                //0未审核, 1审核通过, 2审核不通过
                String aduitStatus;
                if ("0".equalsIgnoreCase(dto.getAduitStatus())) {
                    aduitStatus = "未审核";
                }else if ("1".equalsIgnoreCase(dto.getAduitStatus())) {
                    aduitStatus = "审核通过";
                }else if ("2".equalsIgnoreCase(dto.getAduitStatus())) {
                    aduitStatus = "审核不通过";
                }else {
                    aduitStatus = "";
                }
                hssfCell14.setCellValue(aduitStatus);
                //提交时间
                XSSFCell hssfCell15 = hssfRow.createCell(15);
                hssfCell15.setCellStyle(style);
                hssfCell15.setCellValue(ObjectUtil.isNull(dto.getCreatTime())?"":DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, dto.getCreatTime()));
            }
        }
    }

    /**
     * 3: 总提交人(外部)
     * @param response
     * @param wb
     * @param style
     */
    private void exportExcelFileForExcollectcnt(HttpServletResponse response, XSSFWorkbook wb, XSSFCellStyle style, Long deptId, String deptName, String belongDate) {
        List<Long> childDeptIdList = getDeptTreeIds("Y", deptId);
        //外部人员的总填报信息
        if (CollUtil.isNotEmpty(childDeptIdList)) {
            List<YqInfoCollectDTO> yqInfoCollectDTOList = yqInfoCollectMapper.getYqInfoCollectDTOListByDeptIds(belongDate, childDeptIdList);
            //设置Excel内容数据
            setExcelBody(wb, style, deptName, yqInfoCollectDTOList);
        }
        MyExcelUtil.commonExcelDownload(response, deptName+ "(总提交)-"+DateUtil.today() +".xlsx", wb);
    }

    /**
     *
     * 将图片插入到单元格中
     * @param workbook  workbook对象
     * @param sheet   工作簿对象
     * @param fileUrl  URL
     * @param row  第多少行
     * @param col  第多少列
     * @param scaleX   X轴
     * @param scaleY   Y轴
     * @version
     */
    public static void setPicToCell(XSSFWorkbook workbook, XSSFSheet sheet, String fileUrl, int row, int col, double scaleX, double scaleY) {
        try {
            // 构造URL
            String link = "http://fangkong.hfmri.net:18080/profile/upload/2022/04/06/87968174-c2f0-48cf-b6f6-c780d15febd1_20220406074909A017.png";
//            String link = BASE_URL+fileUrl;
            InputStream is = URLUtil.getStream(new URL(link));
            byte[] bytes = IOUtils.toByteArray(is);
            @SuppressWarnings("static-access")
            int pictureIdx = workbook.addPicture(bytes, workbook.PICTURE_TYPE_PNG);
            CreationHelper helper = workbook.getCreationHelper();
            Drawing drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = helper.createClientAnchor();
            // 图片插入坐标
            anchor.setCol1(col);
            anchor.setRow1(row);
            // 插入图片
            Picture pict = drawing.createPicture(anchor, pictureIdx);
            pict.resize(scaleX, scaleY);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
